package com.hongri.recyclerview.fragment;


import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.hongri.recyclerview.R;
import com.hongri.recyclerview.utils.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author：zhongyao on 2017/4/9 17:32
 * @description:AsyncTask
 */
public class AsyncTaskFragment extends Fragment implements View.OnClickListener{


    public static AsyncTaskFragment asyncTaskFragment;
    private String url;
    private Button serialBtn,parallelBtn;

    public static AsyncTaskFragment getInstance() {
        if (asyncTaskFragment == null){
            asyncTaskFragment = new AsyncTaskFragment();
        }
        return asyncTaskFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_async_task, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        serialBtn = (Button) view.findViewById(R.id.serialBtn);
        parallelBtn = (Button) view.findViewById(R.id.parallelBtn);

        serialBtn.setOnClickListener(this);
        parallelBtn.setOnClickListener(this);

        url = "http://api.csdn.net/user/getmobile";
//        new MyAsyncTask().execute(url);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //串行
            case R.id.serialBtn:
                new MyAsyncTask("MyAsyncTask#1").execute("");
                new MyAsyncTask("MyAsyncTask#2").execute("");
                new MyAsyncTask("MyAsyncTask#3").execute("");
                new MyAsyncTask("MyAsyncTask#4").execute("");
                new MyAsyncTask("MyAsyncTask#5").execute("");
                break;
            //并行
            case R.id.parallelBtn:
                new MyAsyncTask("MyAsyncTask#1").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");
                new MyAsyncTask("MyAsyncTask#2").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");
                new MyAsyncTask("MyAsyncTask#3").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");
                new MyAsyncTask("MyAsyncTask#4").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");
                new MyAsyncTask("MyAsyncTask#5").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");
                break;
        }
    }

    public class MyAsyncTask extends AsyncTask<String, Integer, String> {

        private String name = "MyAsyncTask";
        public MyAsyncTask(String name) {
            super();
            this.name = name;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Logger.d("onPreExecute");
        }

        @Override
        protected String doInBackground(String... params) {
            Logger.d("doInBackground");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return name;
        }

//        @Override
//        protected String doInBackground(String... params) {
//            Logger.d("doInBackground");
//            String result = "";
//
//            publishProgress(0);
//            try {
//                URL url = new URL(params[0]);
//                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//                urlConnection.setReadTimeout(15000);
//                urlConnection.setConnectTimeout(15000);
//                urlConnection.setRequestMethod("GET");
//                urlConnection.setDoInput(true);
//                urlConnection.connect();
//                int  responseCode = urlConnection.getResponseCode();
////                if (responseCode == HttpURLConnection.HTTP_OK){
//                    InputStream is = urlConnection.getInputStream();
//                    result = convertStreamToString(is);
//
//                publishProgress(100);
//                Logger.d("result:"+result);
////                }
//
//
//            } catch (MalformedURLException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            return result;
//        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Logger.d("onProgressUpdate");

            Logger.d("values:"+values[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Logger.d("onPostExecute");
            Logger.d("result:"+result);
        }


    }

    public static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
        final BufferedReader reader = new BufferedReader(new InputStreamReader(
                is));
        final StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        return sb.toString();
    }
}
